﻿using System.Windows;
using System.Windows.Controls;

namespace YKXiangQi.Controls
{
    public class GridSplitterEx: GridSplitter
    {
        private GridLength _rowHeight;
        private GridLength _columnWidth;
        private double _rowMinHeight;
        private double _columnMinWidth;
        private bool _isChanged;

        public GridSplitterEx()
        {
            this.IsVisibleChanged += GridSplitterExIsVisibleChanged;
        }

        void GridSplitterExIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var parent = this.Parent as Grid;
            if (parent == null) return;

            if (ResizeDirection == GridResizeDirection.Rows)
            {
                int rowIndex = Grid.GetRow(this);
                var row = parent.RowDefinitions[rowIndex];

                if (Visibility != Visibility.Visible)
                {
                    _rowHeight = row.Height;
                    _rowMinHeight = row.MinHeight;
                    _isChanged = true;

                    row.MinHeight = 0;
                    row.Height = GridLength.Auto;
                }
                else
                {
                    if (_isChanged)
                    {
                        row.MinHeight = _rowMinHeight;
                        row.Height = _rowHeight;
                    }
                }
            }
            else
            {
                int columnIndex = Grid.GetColumn(this);
                var column = parent.ColumnDefinitions[columnIndex];

                if (Visibility != Visibility.Visible)
                {
                    _columnWidth = column.Width;
                    _columnMinWidth = column.MinWidth;

                    column.MinWidth = 0;
                    column.Width = GridLength.Auto;
                    _isChanged = true;
                }
                else
                {
                    if (_isChanged)
                    {
                        column.MinWidth = _columnMinWidth;
                        column.Width = _columnWidth;
                    }
                }
            }
        }
    }
}
